<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="icon" href="${pageContext.request.contextPath}/lib/static/login/images/favicon.ico">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/lib/layui/css/layui.css">
    <script src="${pageContext.request.contextPath}/lib/static/common/js/jquery.min.js" charset="utf-8"></script>
    <script src="${pageContext.request.contextPath}/lib/layui/layui.js" charset="utf-8"></script>


</head>
<body>
<div class="layui-fluid">
    <div class="layui-row">
        <fieldset class="layui-elem-field layui-field-title">
            <legend>消息公告</legend>
        </fieldset>
    </div>
    <hr class="layui-bg-red">
    <div class="layui-row">
        <div class="layui-col-md-offset1">
            <form class="layui-form">
                <div class="layui-inline">
                    <input class="layui-input" name="criteria" autofocus placeholder="发布者">
                </div>
                <button class="layui-btn layuiadmin-btn-admin" lay-submit="" lay-filter="search">
                    <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                </button>
            </form>
        </div>
    </div>

    <table class="layui-hide" id="test" lay-filter="test"></table>

    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="delNotice">多项删除</button>
            <button class="layui-btn layui-btn-sm" lay-event="addNotice">发布公告</button>
        </div>
    </script>

    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <script>
        layui.use('table', function(){
            var $ = layui.$;
            var table = layui.table;
            var form = layui.form;

            var noticeTable = table.render({
                elem: '#test'
                ,toolbar: '#toolbarDemo'
                ,title: '公告数据表'
                ,url:'${pageContext.request.contextPath}/notice/get'
                /*修改默认向后台传递的页码、大小参数名 @ming*/
                ,request: {
                    pageName: 'pageNo' //页码的参数名称，默认：page
                    ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
                }
                ,height: 'full-150'
                ,cols: [[
                     {type: 'checkbox'}
                    ,{type: 'numbers'}
                    ,{field:'id',           title:'ID',       align: 'center',   unresize: true,  sort: true}
                    ,{field:'type',         title:'公告类型',  align: 'center',
                        templet:function(notice){
                              if( notice.type==0){
                                  return type='通知';
                              }else{
                                  return type='公告';
                              }
                        }
                      }
                    ,{field:'title',        title:'标题',      align: 'center' }
                    ,{field:'context',      title:'公告内容',  align: 'center' ,  }
                    ,{field:'startTime',    title:'发布时间',  align: 'center' , align: 'center',sort: true,templet:'<div>{{layui.laytpl.toDateString(d.addTime)}}</div>'}
                    ,{field:'publisher',    title:'发布者',    align: 'center' ,  }
                    ,{field:'department',   title:'发布部门',  align: 'center' ,  }
                    ,{field:'status',       title:'状态',      align: 'center' , sort: true,
                        templet:function(notice){
                            if( notice.status==0 ){
                                return status='一般';
                            }
                            if( notice.status==1 ){
                                return status='重要';
                            }else{
                                return status='紧急';
                            }

                        }
                    }
                    ,{fixed: 'right',       title:'操作',      align: 'center',toolbar: '#barDemo', width:150}
                ]]
                ,page: {
                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip']
                    ,groups: 5
                }
                ,parseData: function(res){ /*重新解析json*/
                    var data = res.data;
                    /*显示部门名称*/
                    $.each(data, function (index, notice) {
                        notice.department = notice.department
                    });
                    return res;
                }
            });
            //时间戳处理
            layui.laytpl.toDateString=function(d,format){
                var date = new Date(d||new Date())
                    ,ymd=[
                    this.digit(date.getFullYear(),4)
                    ,this.digit(date.getMonth()+1)
                    ,this.digit(date.getDate())
                ]
                    ,hms=[
                    this.digit(date.getHours())
                    ,this.digit(date.getMinutes())
                    ,this.digit(date.getSeconds())
                ];
                format=format||'yyyy-MM-dd HH:mm:ss';
                return format.replace(/yyyy/g,ymd[0])
                    .replace(/MM/g,ymd[1])
                    .replace(/dd/g,ymd[2])
                    .replace(/HH/g,hms[0])
                    .replace(/mm/g,hms[1])
                    .replace(/ss/g,hms[2])
            };
            //数字前置补零
            layui.laytpl.digit = function(num,length,end){
                var str='';
                num = String(num);
                length=length ||2;
                for(var i=num.length;i<length;i++){
                    str +='0';
                }
                return num<Math.pow(10,length) ? str+(num|0):num;
            };

            //头工具栏事件
            table.on('toolbar(test)', function(obj){
                var checkStatus = table.checkStatus(obj.config.id);
                switch(obj.event){
                    //查看详情
                    case 'getFindData':
                        var data = checkStatus.data;
                        layer.alert(JSON.stringify('公告:    '+data[0].context));
                        break;
                    case 'addNotice':
                        layer.open({
                            title: '<h2>添加用户</h2>',                                             //弹出层标示
                            content: ['${pageContext.request.contextPath}/notice/notice_edit'],  //弹出层页面
                            type: 2,                                                                //回现数据
                            maxmin: true,
                            shadeClose: true, //点击遮罩关闭层
                            area: ['800px', '520px'],
                           /* success:function (layero,index) {//弹出层打开后的回调函数
                                var body=layer.getChildFrame('body',index);//获取弹出层的dom元素
                                result=JSON.stringify(data);
                                result=$.parseJSON(result);
                                $.each(result,function (item) {
                                    body.find('#A_'+item).val(result[item]);

                                })
                            }*/
                        });
                        break;
                    case 'delNotice':            //多项删除
                        /*获得要删除的ids*/
                        var data = checkStatus.data;
                        var ids = [];
                        $.each( data, function(index, value){
                            var id = value.id;
                            ids.push(id);
                        });
                        /*根据id删除数据*/
                        deleteNoticeByIds($, ids.toString(), noticeTable,data.length);
                        break;
                    case 'isAll':
                        layer.msg(checkStatus.isAll ? '全选': '未全选');
                        break;
                };
            });

            //监听行工具事件
            table.on('tool(test)', function(obj){
                //当前行数据
                var data = obj.data;
                //console.log(obj)
                var id=data.id;
                var url='${pageContext.request.contextPath}/notice/deleteById';
                //删除功能完善
                if(obj.event === 'del'){
                    $.post(url,{id:id},function () {
                        layer.confirm('您确定要删除吗', function (index) {
                            layer.close(index);
                            obj.del();
                        })
                    })

                } else if(obj.event === 'edit'){        //修改数据页面
                    layer.open({
                        content: ['${pageContext.request.contextPath}/notice/notice_edit'],  //弹出层页面
                        type: 2,
                        title: '<h2>编辑公告</h2>',
                        maxmin: true,
                        shadeClose: true, //点击遮罩关闭层
                        offset: '50px',
                        area: ['800px', '530px'],
                        closeBtn: 2,
                        success: function (layero, index) {             //弹出层打开后的回调函数
                            var body = layer.getChildFrame('body', index);
                            /*按method绑定 新增或者修改事件*/
                            // 取到弹出层里的元素，并把编辑的内容放进去
                            body.find("input[name='id']").val(data.id);//将选中的数据的id传到编辑页面的隐藏域，便于根据ID修改数据
                            body.find("#type").val(data.type);
                            body.find("input[name='title']").val(data.title);
                            body.find("textarea[name='context']").val(data.context);
                            body.find("input[name='publisher']").val(data.publisher);
                            body.find("input[name='department']").val(data.department);
                            body.find("#status").val(data.status);
                            layer.iframeAuto(index);
                            body.find("[lay-submit]").attr("lay-filter", "edit");
                            return false;
                        }
                    });
                }
            });

            //模糊查询
            form.on('submit(search)', function(data){
                noticeTable.reload({
                    url: '${pageContext.request.contextPath}/notice/get'
                    ,method:"post" /*解决参数传递中文乱码*/
                    ,where: data.field
                });

                return false;
            });
        });
        //多选删除请求
        function deleteNoticeByIds($, ids, noticeTable,len) {
            /*多项删除时没有选择数据时给出提示*/
            if (len < 1) {
                layer.alert('请至少选择一条您要删除的数据', {
                    skin: 'layui-layer-molv'
                    , closeBtn: 0
                });
                return;
            }
            layer.confirm("您选中了" + len + "条数据，确认删除？", function(index){
                /*发送ajax请求访问后台*/
              //  var url='/notice/deleteByIds';
                $.post(
                    '${pageContext.request.contextPath}/notice/deleteByIds',
                    {ids: ids},
                    function (result) {
                        console.log(result);
                        if (result.code == 0) {
                            layer.msg(result.msg, {icon: 1});
                            /*刷新表格数据*/
                            noticeTable.reload({
                                url: '${pageContext.request.contextPath}/notice/get',
                            });
                        } else {
                            layer.msg(result.msg, {icon: 5});
                        }
                    },
                    "json"
                );
            });
        }
    </script>
    <script type="text/javascript">

    </script>
</div>
</body>
</html>
